#include <QDesktopServices>
#include <QDebug>
#include <QPainter>
#include <QPaintEvent>
#include <QMouseEvent>
#include <QTimer>
#include "widget.h"




Widget::Widget(QWidget *parent)
    : QGLWidget(parent),
      spriteBatch(0),
      font(0)
{
    // Startup the timer which will call updateGL as fast as it can.
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateGL()));
    timer->start();

    renderAngle = 0.0f;

    setAutoFillBackground( false );
    setAttribute (Qt::WA_OpaquePaintEvent);
    setAttribute( Qt::WA_NoSystemBackground );
    setAttribute( Qt::WA_NativeWindow );
    setAttribute( Qt::WA_PaintOnScreen, true );
    setAttribute( Qt::WA_StyledBackground,false);
    setAutoBufferSwap(false);
}


Widget::~Widget()
{
    destroyGL();
}

void Widget::resizeGL(int w, int h)
{
    // Reset the GL viewport for current resolution.
    glViewport(0,0, w, h);
    if (spriteBatch) {
        spriteBatch->setTargetSize( w,h );
    }
}


void Widget::initializeGL() {
    glClearColor(0,0,0,0);
    glDisable(GL_CULL_FACE);
    if (spriteBatch) delete spriteBatch;
    spriteBatch = new QtOpenGLSpriteBatch(width(), height(), this );
    font = new SpriteBatchBMFont(":/assets/font.fnt", "assets/font_0.png");
}

void Widget::destroyGL() {
    if (font) delete font;
    font = 0;
    if (spriteBatch) delete spriteBatch;
    spriteBatch = 0;
}


void Widget::renderTextToCenter( const char *text, float xoffset, float y, float size,
                                 float angle, float r, float g, float b, float a) {
    font->writeText(spriteBatch, text,
                    (spriteBatch->getTargetWidth()-font->getTextLength(text,size))/2.0f + xoffset,
                    y, size, angle, r,g,b,a );
}

void Widget::paintGL() {
    QTime cTime = QTime::currentTime();
    float frameTime = (float)prevTime.msecsTo( cTime ) / 1000.0f;
    prevTime = cTime;

    renderAngle+=frameTime;


    // Clear the background and depth-buffer for this frame
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    spriteBatch->begin();

    renderTextToCenter("OpenGL ES 2", cosf( renderAngle )*64.0f, 100,100,0,1,1,1,1);
    renderTextToCenter("rendered text", 0.0f, 200,64,sinf(renderAngle*1.8f)*0.1f,1,1,0,1);

    renderTextToCenter("with the spritebatch", 0.0f, 300,48,0.0f,0,1,1,1);




    spriteBatch->end();

    // Swap buffers manually (automatic swapping disabled).
    swapBuffers();
}


